package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.*;

/**
 * 体检套餐服务
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService{
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;

    //新增套餐信息，同时需要关联检查组
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckgroup(setmealId,checkgroupIds);
        //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //目前移动端的套餐列表页面和套餐详情页面每次展示都需要查询数据库，现在需要将这些套餐信 息放入redis缓存来提高查询性能
    public List<Setmeal> findAll() {
        //检查redis是否有数据
        Set<String> setmeals = jedisPool.getResource().zrange("setmeals", 0, -1);
        List<Setmeal> list = null;
        //判断查询的集合是否为空
        if (setmeals == null || setmeals.size() == 0) {
            //如果为空，从数据库查询并存入redis
            list = setmealDao.findAll();
            for (Setmeal setmeal : list) {
                String s = JSON.toJSON(setmeal).toString();
                jedisPool.getResource().zadd("setmeals",setmeal.getId(),s);
            }
        } else {
            //如果不为空，将set的数据存入list
            list = new ArrayList<Setmeal>();
            Setmeal setmeal = null;
            for (String s : setmeals) {
                setmeal = new Setmeal();
                JSONObject jsonObject = JSON.parseObject(s);
                setmeal.setId(jsonObject.getInteger("id"));
                setmeal.setName(jsonObject.getString("name"));
                setmeal.setCode(jsonObject.getString("code"));
                setmeal.setHelpCode(jsonObject.getString("helpCode"));
                setmeal.setSex(jsonObject.getString("sex"));
                setmeal.setAge(jsonObject.getString("age"));
                setmeal.setPrice(jsonObject.getFloat("price"));
                setmeal.setRemark(jsonObject.getString("remark"));
                setmeal.setAttention(jsonObject.getString("attention"));
                setmeal.setImg(jsonObject.getString("img"));
                list.add(setmeal);
            }
        }
        return list;
    }

    //根据套餐ID查询套餐详情（套餐基本信息、套餐对应的检查组信息、检查组对应的检查项信息）
    public Setmeal findById(int id) {
        //检查redis是否有数据
        String idStr = String.valueOf(id);
        String setmealStr = jedisPool.getResource().get(idStr);
        Setmeal setmeal = null;
        //判断查询的对象是否为空
        if (setmealStr == null) {
            //如果为空，从数据库查询并存入redis
            setmeal = setmealDao.findById(id);
            String json = JSON.toJSON(setmeal).toString();
            //如果查询结果为空，保存redis在60秒
            if (json == null || "".equals(json)) {
                jedisPool.getResource().setex(idStr,60,json);
            } else {
                //设置保存10~20天的过期时间，防止缓存雪崩
                int second = (int) (Math.random() * 60 * 60 * 24 * 10);
                jedisPool.getResource().setex(idStr,second+60*60*24*10,json);
            }
        } else {
            //如果不为空，将set的数据存入list
            setmeal = new Setmeal();
            JSONObject jsonObject = JSON.parseObject(setmealStr);
            setmeal.setId(jsonObject.getInteger("id"));
            setmeal.setName(jsonObject.getString("name"));
            setmeal.setCode(jsonObject.getString("code"));
            setmeal.setHelpCode(jsonObject.getString("helpCode"));
            setmeal.setSex(jsonObject.getString("sex"));
            setmeal.setAge(jsonObject.getString("age"));
            setmeal.setPrice(jsonObject.getFloat("price"));
            setmeal.setRemark(jsonObject.getString("remark"));
            setmeal.setAttention(jsonObject.getString("attention"));
            setmeal.setImg(jsonObject.getString("img"));
            List<CheckGroup> checkGroups = (List<CheckGroup>) jsonObject.get("checkGroups");
            setmeal.setCheckGroups(checkGroups);
        }
        return setmeal;
    }

    //查询套餐预约占比数据
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    @Override
    public List<Map<String, Object>> getSex() {
        return setmealDao.findSex();
    }

    @Override
    public List<Map<String, Object>> getAge() {
        return setmealDao.findAge();
    }

    //设置套餐和检查组多对多关系，操作t_setmeal_checkgroup
    public void setSetmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds){
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }
}
